package com.ruoyi.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.ProcessInstance;
import com.ruoyi.mapper.ProcessInstanceMapper;
import com.ruoyi.service.ProcessInstanceService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【流程实例】Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-04-30
 */
@Service
public class ProcessInstanceServiceImpl implements ProcessInstanceService {
    @Autowired
    private ProcessInstanceMapper processInstanceMapper;

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysPostMapper postMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysDeptMapper deptMapper;
//    @Autowired
//    private ActBusinessRefinfoMapper actBusinessRefinfoMapper;
//
//    @Autowired
//    private ActRuTaskMapper actRuTaskMapper;
    /**
     * 查询流程实例
     * 
     * @param id 流程实例ID
     * @return 流程实例
     */
    @Override
    public ProcessInstance selectActProcinstById(String id)
    {
        return processInstanceMapper.selectActProcinstById(id);
    }

    /**
     * 查询流程实例列表
     * 
     * @param processInstance 流程实例
     * @return 流程实例
     */
    @Override
    public List<ProcessInstance> selectActProcinstList(ProcessInstance processInstance)
    {
        //List<SysDept> sysDepts = deptMapper.selectAllInstByUserId(Long.valueOf(ShiroUtils.getUserId()));
        /*String deptIds= "";
        for(SysDept sysDept:sysDepts){
            deptIds+=sysDept.getDeptId()+",";
        }
        processInstance.setDeptIds(deptIds);*/

        List<ProcessInstance> processInstances = processInstanceMapper.selectActProcinstList(processInstance);
        Map<String, String> userPostRole = getUserPostRole();
        for(ProcessInstance procinst: processInstances){
            String assignee = "";
            if(StringUtils.isNotEmpty(procinst.getAssignee())){
                assignee = transformationName(procinst.getAssignee(),userPostRole);
                procinst.setAssignee(assignee);
            }


        }
        return processInstances;
    }

    /**
     * 新增流程实例
     * 
     * @param processInstance 流程实例
     * @return 结果
     */
    @Override
    public int insertActProcinst(ProcessInstance processInstance)
    {
        return processInstanceMapper.insertActProcinst(processInstance);
    }

    /**
     * 修改流程实例
     * 
     * @param processInstance 流程实例
     * @return 结果
     */
    @Override
    public int updateActProcinst(ProcessInstance processInstance)
    {
        return processInstanceMapper.updateActProcinst(processInstance);
    }

    /**
     * 删除流程实例对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteActProcinstByIds(String ids)
    {
        return processInstanceMapper.deleteActProcinstByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除流程实例信息
     * 
     * @param businessId 业务表ID
     * @return 结果
     */
//    @Override
//    @Transactional
//    public int deleteActProcinstById(String businessId,String tableName) throws Exception {
//        try {
//            String userName = ShiroUtils.getSysUser().getUserName();
//            ActBusinessRefinfo actBusinessRefinfo = new ActBusinessRefinfo();
//            actBusinessRefinfo.setBusinessId(businessId);
//            actBusinessRefinfo.setTableName(tableName);
//            actBusinessRefinfo = actBusinessRefinfoMapper.selectActBusinessRefinfoByBus(actBusinessRefinfo);
//            processInstanceMapper.delProcInst(actBusinessRefinfo.getProcinstId());
//            actRuTaskMapper.updatebBusinessStatus(actBusinessRefinfo.getBusinessId(), actBusinessRefinfo.getTableName().split("\\.")[0], BusinessStatus.NOT_APPLIED.getCode(), actBusinessRefinfo.getTableName().split("\\.")[1],userName,new Date());
//
//            //BaseBpmn bas eBpmn = new BaseBpmn();
//            //baseBpmn.deleteProcessInst(id);
//        }catch(Exception e){
//            throw new Exception("撤回流程实例失败");
//        }
//        return 1;
//
//    }

    /**
     * 删除流程实例信息
     *
     * @param id 流程实例ID
     * @return 结果
     */
//    @Override
//    @Transactional
//    public int deleteActProcinstById(String id) throws Exception {
//        try {
//            String userName = ShiroUtils.getSysUser().getUserName();
//            ActBusinessRefinfo actBusinessRefinfo = null;
//            //actBusinessRefinfo.setBusinessId(businessId);
//            //actBusinessRefinfo.setTableName(tableName);
//            actBusinessRefinfo = actBusinessRefinfoMapper.selectActBusinessRefinfoByProcInstId(id);
//            processInstanceMapper.delProcInst(actBusinessRefinfo.getProcinstId());
//
//
//            actRuTaskMapper.updatebBusinessStatus(actBusinessRefinfo.getBusinessId(), actBusinessRefinfo.getTableName().split("\\.")[0], BusinessStatus.NOT_APPLIED.getCode(), actBusinessRefinfo.getTableName().split("\\.")[1],userName,new Date());
//        }catch (Exception e){
//            throw new Exception("删除流程实例失败");
//        }
//
//        return 1;
//
//    }



    /**
     * 查询【当前人办理历史】列表
     *
     * @param processInstance 流程实例
     * @return 流程实例
     */
    @Override
    public List<ProcessInstance> selectHandleHiProcinstList(ProcessInstance processInstance)
    {
        //
        Long userId = ShiroUtils.getUserId();
        processInstance.setCreateBy(userId+"");
        List<ProcessInstance> processInstances = processInstanceMapper.selectHandleHiProcinstList(processInstance);
        Map<String, String> userPostRole = getUserPostRole();
        for(ProcessInstance procinst: processInstances){
            String assignee = "";
            if(StringUtils.isNotEmpty(procinst.getAssignee())){
                assignee = transformationName(procinst.getAssignee(),userPostRole);
                procinst.setAssignee(assignee);
            }


        }

        return processInstances;
    }

    /**
     * 查询【当前人办理历史】列表 App端
     *
     * @param processInstance 流程实例
     * @return 流程实例
     */
    @Override
    public List<ProcessInstance> selectAppHandleHiProcinstList(ProcessInstance processInstance, String userId)
    {

        processInstance.setCreateBy(userId);

        List<ProcessInstance> processInstances = processInstanceMapper.selectHandleHiProcinstList(processInstance);
        Map<String, String> userPostRole = getUserPostRole();
        for(ProcessInstance procinst: processInstances){
            String assignee = "";
            if(StringUtils.isNotEmpty(procinst.getAssignee())){
                assignee = transformationName(procinst.getAssignee(),userPostRole);
                procinst.setAssignee(assignee);
            }


        }

        return processInstances;
    }

    @Override
    public List<ProcessInstance> selectAppHandleHiProcinstAppList(ProcessInstance processInstance, String userId) {
        processInstance.setCreateBy(userId);

        List<ProcessInstance> processInstances = processInstanceMapper.selectHandleHiProcinstAppList(processInstance);
        Map<String, String> userPostRole = getUserPostRole();
        for(ProcessInstance procinst: processInstances){
            String assignee = "";
            if(StringUtils.isNotEmpty(procinst.getAssignee())){
                assignee = transformationName(procinst.getAssignee(),userPostRole);
                procinst.setAssignee(assignee);
            }


        }
        return processInstances;
    }


    private Map<String, String> getUserPostRole()
    {

        Map<String,String> map = new HashMap<String,String>();
        List<SysRole> roles  = roleMapper.selectRoleList(new SysRole());
        List<SysUser> users = userMapper.selectUserList(new SysUser());
        List<SysPost> posts = postMapper.selectPostAll();
        for(SysRole role:roles){
            map.put("@role_"+role.getRoleId()+"@",role.getRoleName());
        }
        for(SysUser user:users){
            map.put("@user_"+user.getUserId()+"@",user.getUserName());
        }
        for(SysPost post:posts){
            map.put("@post_"+post.getPostId()+"@",post.getPostName());
        }
        return map;
    }
    /**
     *  @param idstr ID字符串 @post_18@
     * */
    public String transformationName(String idstr,Map<String, String> userPostRole){

        String arr[] = idstr.split(",");
        String userTran = "【用户】";
        String roleTran = "【角色】";
        String postTran = "【岗位】";
        for(int i=0;i<arr.length;i++){
            if(StringUtils.isNotEmpty(arr[i])){
                if("@user".equals(arr[i].split("_")[0])){
                    userTran+=userPostRole.get(arr[i])+",";
                }
                if("@role".equals(arr[i].split("_")[0])){
                    roleTran+=userPostRole.get(arr[i])+",";
                }
                if("@post".equals(arr[i].split("_")[0])){
                    postTran+=userPostRole.get(arr[i])+",";
                }
            }
        }
        String returnNames = "";
        if(userTran!="【用户】"){
            returnNames+=userTran;
        }
        if(roleTran != "【角色】"){
            returnNames+=roleTran;
        }
        if(postTran != "【岗位】"){
            returnNames+=postTran;
        }
        return returnNames;
    }
}
